package tjcu.archives.config;

import com.alibaba.druid.util.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import tjcu.archives.entity.User;
import tjcu.archives.service.MenuService;

public class UserRealm extends AuthorizingRealm {
    public static final int HASH_ITERATIONS = 1024;

    {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");
        matcher.setHashIterations(HASH_ITERATIONS);
        this.setCredentialsMatcher(matcher);
    }

    @Autowired
    private MenuService menuService;

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取的前台username
        //1. 获取用户名
        String loginName = (String) authenticationToken.getPrincipal();

        //2. 判断用户名
        if (StringUtils.isEmpty(loginName)) {
            throw new RuntimeException("【登录功能】 用户名不能为空！");
        }

        //3. 根据用户名查询
        User sysUser = menuService.loginname(loginName);

        //4. 判断查询结果
        if (sysUser == null) {
            throw new RuntimeException("【登录功能】 用户名不正确！");
        }

        //5. 封装返回结果
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sysUser, sysUser.getPassword(), "UserRealm");

        //6. 设置盐
        info.setCredentialsSalt(ByteSource.Util.bytes(sysUser.getSalt()));

        //7. 返回
        return info;
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

}
